package com.example.badyloans.controller;

import com.example.badyloans.common.ReturnResult;
import com.example.badyloans.dao.TLoginLogMapper;
import com.example.badyloans.dao.TUserAccountMapper;
import com.example.badyloans.dao.TUserWalletMapper;
import com.example.badyloans.pojo.*;
import com.example.badyloans.servlet.TLoginLogService;
import com.example.badyloans.servlet.TSystemDictionaryItemService;
import com.example.badyloans.servlet.TUserAccountService;
import com.example.badyloans.servlet.TUserInfoService;
import com.example.badyloans.util.MD5;
import com.example.badyloans.util.PageSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.bytebuddy.asm.Advice;
import org.apache.catalina.connector.Request;
import org.apache.ibatis.logging.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FilenameUtils;
import org.w3c.dom.Element;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.locks.Condition;

/**
 * @author 啊桥哦
 * @Description:
 * @date 2020-07-12 20:10
 */
@Api("用户管理相关控制器")
@RestController
public class UserController {

    private  static final  Logger log= LoggerFactory.getLogger(UserController.class);
    @Resource
    private TUserAccountService tUserAccountService;
    @Resource
    private TLoginLogMapper tLoginLogMapper;
    @Resource
    private TUserWalletMapper tUserWalletMapper;
    @Resource
    private TSystemDictionaryItemService tSystemDictionaryItemService;
    @Resource
    private TUserInfoService tUserInfoService;
    @Resource
    private TLoginLogService tLoginLogService;

        /**
         * 检查用户名是否存在
         * @param username
         * @return
         */
        @ApiOperation("检查用户名是否存在")
        @PostMapping(value ="/user/checkUsername")
        public boolean checkUsername(@ApiParam(name="username",value ="要校检的用户名") @RequestParam String username){
            //判断用户名是否重复
            if(StringUtils.isEmpty(username)){
                return false;
            }
            //调用查询用户名的方法，返回boolean类型
            boolean bool=tUserAccountService.countUserAccountUsername(username);
            return bool;
        }

        /**
         * 新增用户TUSER
         * @param tUserAccount
         * @param request
         * @return
         */
        @ApiOperation("新增用户TUSER")
        @PostMapping(value = "/user/register")
        public  ReturnResult insertTUserAccount(TUserAccount tUserAccount, HttpServletRequest request){
            if (StringUtils.isEmpty(tUserAccount)){
                return ReturnResult.fail("该值为空");
            }
            ReturnResult returnResult=tUserAccountService.insertSelective(tUserAccount);
            return returnResult;
        }

         /**
         * 登陆用户
         * @param tUserAccount
         * @param request
         * @return
         */
        @ApiOperation("登陆用户")
        @PostMapping("/user/login")
        public ReturnResult dengluTUserAccount(TUserAccount tUserAccount,HttpServletRequest request){
            //把密码进行MD5验证
            String pass=MD5.encode(tUserAccount.getPassword());
            TUserAccount tUserAccount1=tUserAccountService.countUserAccountdenglu1(tUserAccount.getUsername(),pass);
            //拿到当前ip地址
            String ip=request.getRemoteAddr();
            //拿到前台登陆id
            Integer id=tUserAccount.getAccountType();
            //判断是运营人员还是普通人员
            try{
                if(StringUtils.isEmpty(tUserAccount1.getAccountType())){
                    return ReturnResult.fail("登陆失败，账号或者密码错误");
                }
            }catch (Exception e){
                return ReturnResult.fail("登陆失败，账号或者密码错误");
            }
            if(tUserAccount1.getAccountType()==id){
                //false为登陆成功
                if(tUserAccount1!=null){
                    //登陆成功后 把登陆信息记录到 tloginlog表中
                    TLoginLog tLoginLog=new TLoginLog();
                    tLoginLog.setIp(ip);
                    tLoginLog.setLoginTime(LocalDateTime.now());
                    tLoginLog.setUsername(tUserAccount.getUsername());
                    tLoginLog.setAccountType(tUserAccount1.getAccountType());
                    tLoginLog.setLoginResult(1);
                    tLoginLog.setCreateTime(tUserAccount.getCreateTime());
                    int count=tLoginLogMapper.insertSelective(tLoginLog);
                    if (count>0){
                        //前台session
                        request.getSession().setAttribute("tUserAccount1",tUserAccount1);
                    }else{
                        log.info("新增失败");
                    }
                    return ReturnResult.success(tUserAccount1,null);
                }else{
                    //登陆失败也需要记录到日志表中
                    TLoginLog tLoginLog=new TLoginLog();
                    tLoginLog.setIp(ip);
                    tLoginLog.setLoginTime(LocalDateTime.now());
                    tLoginLog.setUsername(tUserAccount.getUsername());
                    tLoginLog.setAccountType(tUserAccount1.getAccountType());
                    tLoginLog.setLoginResult(0);
                    tLoginLog.setCreateTime(tUserAccount.getCreateTime());
                    int count=tLoginLogMapper.insertSelective(tLoginLog);
                    if (count>0){
                        log.info("新增成功");
                    }else{
                        log.info("新增失败");
                    }
                    return ReturnResult.fail("登陆失败，账号或者密码错误");
                }
            }else {
                if(tUserAccount1.getAccountType()==1){
                    return ReturnResult.fail("普通人员不是从这里登陆");
                }else if(tUserAccount1.getAccountType()==2){
                    return ReturnResult.fail("运营人员不是从这里登陆");
                }
                return ReturnResult.fail("登陆失败，账号或者密码错误");
            }
        }

        /**
         *注销之后清除后台session值
         * @param request
         * @param response
         * @throws IOException
         */
        @ApiOperation(value = "清除session")
        @GetMapping("/zhuxiao")
        public void zhuxiaodenglu(HttpServletRequest request, HttpServletResponse response) throws IOException {
            request.getSession().removeAttribute("tUserAccount");
            response.sendRedirect("index.html");
        }

        /**
         * 查询下拉框
         * @return
         */
        @ApiOperation("查询下拉框")
        @GetMapping("system/dictionaryItem/getAll")
        public ReturnResult dictionaryitem(){
            List<TSystemDictionaryItem> list=null;
            list =tSystemDictionaryItemService.selectchaxunquanbu();
            return ReturnResult.success(list,null);
        }

        /**
         * 修改资料
         * @param tUserInfo
         * @return
         */
        @ApiOperation("修改资料")
        @PostMapping("user/userinfo/update")
        public ReturnResult updateDiction(TUserInfo tUserInfo){
            if (StringUtils.isEmpty(tUserInfo)) {
                return ReturnResult.fail("该对象为空");
            }
            ReturnResult returnResult=tUserInfoService.updateByPrimaryKeySelective(tUserInfo);
           return returnResult;
        }

        /**
         * 上传文件
         * @param request
         * @param multipartFile
         * @return
         */
        @ApiOperation("上传文件")
        @PostMapping("user/userinfo/uploadAvatar")
        public ReturnResult  uploadAvatar(HttpServletRequest request,@RequestParam(value = "file") MultipartFile multipartFile){
            String arrats="avatar";
            //获得文件上传路劲
            String wenjian="D:/badyloans/src/main/resources/static/avatar";
            //源文件
            String oldFileName=multipartFile.getOriginalFilename();
            //判断文件是否为空
            if(oldFileName!=null){
                //拿到文件后缀
                String prefix=oldFileName.substring(oldFileName.lastIndexOf("."));
                List<String> prefixs= Arrays.asList(".JPG",".PNG",".jpeg",".pneg");
                if (!prefixs.contains(prefix)){
                    return ReturnResult.fail("文件错误，不包含");
                }
                String fileName=System.currentTimeMillis()+Math.abs(new Random().nextLong())+prefix;
                File targetFile=new File(wenjian,fileName);
                if (!targetFile.exists()){
                    targetFile.mkdirs();
                }
                if(multipartFile.getSize()>500000){
                    return ReturnResult.fail("上传失败，文件类型太大");
                }
                try {
                    multipartFile.transferTo(targetFile);
                }catch(Exception e){
                    e.printStackTrace();
                    return ReturnResult.fail("上传失败，");
                }
                arrats = fileName;
            }else{
                return ReturnResult.fail("上传失败");
            }
            return ReturnResult.success(arrats,null);
        }

        /**
         * 登陆日志分页查询
         * @param loginlog
         * @return
         */
        @ApiOperation("登陆日志分页查询")
        @RequestMapping("system/loginlog/query")
        public ReturnResult loginlogquery(loginlog loginlog){
            PageSupport page=new PageSupport();
            page.setPageSize(6);
            page.setTotalCount(tLoginLogService.selectBy(loginlog.getAccountType(),loginlog.getUsername(),loginlog.getLoginResult(),loginlog.getBeginDate(),loginlog.getEndDate())); //查询总记录数
            page.setCurrentPageNo(loginlog.getCurrentPage());
            Integer pageSize=page.getPageSize();       //拿到页大小
            Integer currentPageNo=page.getCurrentPageNo(); //拿到页码
            List<TLoginLog> list=tLoginLogService.selecttrecharge(loginlog.getAccountType(),loginlog.getUsername(),((currentPageNo-1)*pageSize),pageSize,loginlog.getBeginDate(),loginlog.getEndDate(),loginlog.getLoginResult());
            if (list==null){
                return  ReturnResult.fail("没有数据");
            }
            return ReturnResult.success(list,page);
        }
}